/**
 * ${table.comment!} 控制层
 */

import React from "react";
import ${entity}Service from "../service/${entity}Service";
import { message, Modal } from "antd";

export default class ${entity}Controller extends React.Component {
    constructor(props) {
        super(props);
        this.${entity?uncap_first}Service = new ${entity}Service(this.props);
    }

    state = {
        total: 0,
        pageList: [],
        editData: {}
    }

    // 设置 timer：防止组件已经卸载，异步操作中或设置状态方法还在执行
    componentDidMount() {
        this.timer = setTimeout(() => {
            this.get${entity}PageList();
        }, 0);
    }

    // 清除 timer：防止组件已经卸载，异步操作中或设置状态方法还在执行
    componentWillUnmount() {
        clearTimeout(this.timer);
    }

    /**
     * 查询
     */
    get${entity}PageList = (page, pageSize) => {
        let formData = this.$searchForm.props.form.getFieldsValue();

        this.${entity?uncap_first}Service.get${entity}PageList({
            ...formData,
            reqPageNum: page || this.$${entity?uncap_first}Table.state.reqPageNum,
            reqPageSize: pageSize || this.$${entity?uncap_first}Table.state.reqPageSize
        }).then(res => {
            if (res.code !== "200") {
                message.error(res.msg);
                return;
            }

            const pageList = res.data.list.map((item, index) => {
                return {
                    ...item,
                    key: item.id
                };
            });
            this.setState({
                total: res.data.total,
                pageList: pageList
            });
        });
    };

    // 删除
    handleRemove = id => {
        this.modalRemove([id]);
    };
    // 批量删除
    batchHandleRemove = () => {
        const rowKeys = this.selectRowKeys();
        rowKeys.length && this.modalRemove(rowKeys);
    };

    modalRemove = (ids) => {
        Modal.confirm({
            title: "确认",
            centered: true,
            content: "请确认是否删除？",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                this.${entity?uncap_first}Service.batchDelete${entity}(ids).then(data => {
                    if (data.code !== "200") {
                        message.error(data.msg);
                        return;
                    }

                    this.get${entity}PageList();
                });
            }
        });
    }

    selectRowKeys = () => {
        const { selectedRowKeys } = this.$${entity?uncap_first}Table.state;
        if (selectedRowKeys.length <= 0) {
            message.error("请至少选择一条数据");
            return [];
        }
        return selectedRowKeys;
    }

    // 新增
    handleAdd = () => {
        this.setState({
            isAdd: true,
            showModal: true,
            editData: {}
        });
    };

}
